package cn.edu.scau.cmi.hekaimin.compositePattern.consistent;

import javafx.fxml.FXML;

import javafx.scene.control.Button;

import java.util.Iterator;
import java.util.Random;

import cn.edu.scau.cmi.hekaimin.client.ConsistentCompositeClient;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.scene.control.ListView;

public class CCompositePatternController {
	@FXML
	private Button btn_1;
	@FXML
	private Button btn_2;
	@FXML
	private ListView listView;
    private ObservableList<String> strList = FXCollections.observableArrayList();
    OrganizationComposite root = new OrganizationComposite("root");
    public String getRandomString() {
    	String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
        Random random = new Random();  
        StringBuffer sb = new StringBuffer();
        
        for (int i = 0; i < 5; ++i) {  
            
            sb.append(str.charAt(random.nextInt(62)));  
        }      
		return sb.toString();  
        
    }
    public String getRandomOrg() {
    	return "Org-"+ getRandomString();
    }
    public String getRandomPerson() {
    	return "Person-"+ getRandomString();
    }
    
	@FXML
	public void addOrganization(ActionEvent event) {
		String str = getRandomOrg();
		root.add(new OrganizationComposite(str));
		//Iterator<OrganizationComponent>  children = root.getChildren();
		strList.add(str);
		listView.setItems(strList);	
		
	}
	
	@FXML
	public void addPerson(ActionEvent event) {
		String str = getRandomPerson();
		root.add(new Person(str));
		//Iterator<OrganizationComponent>  children = root.getChildren();
		strList.add(str);
		
		listView.setItems(strList);
	}
	@FXML
	public void mouseClicked(MouseEvent event) {
		if(event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
			int index = listView.getSelectionModel().getSelectedIndex();
			//组织
			OrganizationComponent child =  root.getChildren().get(index);
			if(child.detail().charAt(0) == 'O') {
				new ConsistentCompositeClient().init(new Stage());
			}
			
		}
		
	}
	
}
